/**
 * 波次系统 - 管理游戏波次和难度递增
 */
import { System, World, Entity } from '../ecs';
import { WaveManager, GameState, EnemyAI } from '../components';

interface WaveConfig {
  enemyCount: number;
  enemyTypes: Array<{
    type: 'scout' | 'destroyer' | 'mothership';
    count: number;
    spawnDelay: number;
  }>;
  spawnInterval: number;
  bonusScore: number;
}

export class WaveSystem implements System {
  priority = 70;
  private waveConfigs: WaveConfig[] = [
    // 第1波 - 简单
    {
      enemyCount: 5,
      enemyTypes: [{ type: 'scout', count: 5, spawnDelay: 0.5 }],
      spawnInterval: 1.5,
      bonusScore: 500
    },
    // 第2波 - 混合
    {
      enemyCount: 8,
      enemyTypes: [
        { type: 'scout', count: 6, spawnDelay: 0.3 },
        { type: 'destroyer', count: 2, spawnDelay: 1.0 }
      ],
      spawnInterval: 1.2,
      bonusScore: 800
    },
    // 第3波 - 困难
    {
      enemyCount: 12,
      enemyTypes: [
        { type: 'scout', count: 8, spawnDelay: 0.2 },
        { type: 'destroyer', count: 3, spawnDelay: 0.8 },
        { type: 'mothership', count: 1, spawnDelay: 2.0 }
      ],
      spawnInterval: 1.0,
      bonusScore: 1200
    }
  ];

  private currentSpawnQueue: Array<{
    type: 'scout' | 'destroyer' | 'mothership';
    spawnTime: number;
  }> = [];
  
  private nextSpawnTime = 0;

  update(deltaTime: number, world: World): void {
    const waveManager = this.getWaveManager(world);
    const gameState = this.getGameState(world);
    
    if (!waveManager || !gameState || gameState.gameOver) return;

    const currentTime = performance.now() / 1000;

    if (!waveManager.isWaveActive) {
      // 检查是否可以开始新波次
      if (currentTime - waveManager.waveStartTime >= waveManager.timeBetweenWaves) {
        this.startNextWave(world, waveManager, gameState, currentTime);
      }
    } else {
      // 处理当前波次
      this.updateCurrentWave(world, waveManager, gameState, currentTime);
    }
  }

  private getWaveManager(world: World): WaveManager | null {
    const entities = Array.from(world.entities).filter(e => e.hasComponent('waveManager'));
    return entities.length > 0 ? entities[0].getComponent<WaveManager>('waveManager') || null : null;
  }

  private getGameState(world: World): GameState | null {
    const entities = Array.from(world.entities).filter(e => e.hasComponent('gameState'));
    return entities.length > 0 ? entities[0].getComponent<GameState>('gameState') || null : null;
  }

  private startNextWave(world: World, waveManager: WaveManager, gameState: GameState, currentTime: number): void {
    waveManager.isWaveActive = true;
    waveManager.waveStartTime = currentTime;
    
    // 获取波次配置（如果超出预定义波次，使用最后一个配置并增加难度）
    const waveIndex = Math.min(waveManager.currentWave - 1, this.waveConfigs.length - 1);
    const baseConfig = this.waveConfigs[waveIndex];
    
    // 为高波次增加难度
    const difficultyMultiplier = Math.max(1, waveManager.currentWave - this.waveConfigs.length + 1);
    
    // 生成敌机队列
    this.generateSpawnQueue(baseConfig, difficultyMultiplier, currentTime);
    
    // 更新敌机剩余数量
    waveManager.enemiesRemaining = this.currentSpawnQueue.length;
    
    console.log(`🌊 第 ${waveManager.currentWave} 波开始！敌机数量: ${waveManager.enemiesRemaining}`);
  }

  private generateSpawnQueue(config: WaveConfig, difficultyMultiplier: number, startTime: number): void {
    this.currentSpawnQueue = [];
    let spawnTime = startTime + 1; // 1秒后开始生成
    
    for (const enemyType of config.enemyTypes) {
      const count = Math.floor(enemyType.count * difficultyMultiplier);
      
      for (let i = 0; i < count; i++) {
        this.currentSpawnQueue.push({
          type: enemyType.type,
          spawnTime: spawnTime
        });
        
        spawnTime += enemyType.spawnDelay / difficultyMultiplier; // 难度越高生成越快
      }
    }
    
    // 随机打乱生成顺序
    this.shuffleArray(this.currentSpawnQueue);
    
    // 重新分配生成时间，保持间隔
    const interval = config.spawnInterval / Math.sqrt(difficultyMultiplier);
    for (let i = 0; i < this.currentSpawnQueue.length; i++) {
      this.currentSpawnQueue[i].spawnTime = startTime + 1 + (i * interval);
    }
  }

  private updateCurrentWave(world: World, waveManager: WaveManager, gameState: GameState, currentTime: number): void {
    // 生成队列中的敌机
    this.spawnQueuedEnemies(world, currentTime);
    
    // 检查当前存活的敌机数量
    const aliveEnemies = Array.from(world.entities).filter(e => e.hasComponent('enemyAI')).length;
    
    // 如果所有敌机都被消灭且生成队列为空
    if (aliveEnemies === 0 && this.currentSpawnQueue.length === 0) {
      this.completeWave(waveManager, gameState);
    }
  }

  private spawnQueuedEnemies(world: World, currentTime: number): void {
    // 从队列中生成到时间的敌机
    while (this.currentSpawnQueue.length > 0 && 
           this.currentSpawnQueue[0].spawnTime <= currentTime) {
      
      const enemyToSpawn = this.currentSpawnQueue.shift()!;
      this.spawnEnemy(world, enemyToSpawn.type);
    }
  }

  private spawnEnemy(world: World, type: 'scout' | 'destroyer' | 'mothership'): void {
    const { width } = world.resources;
    const x = Math.random() * (width - 100) + 50;
    
    let enemy: Entity;
    
    switch (type) {
      case 'scout':
        enemy = this.createScoutEnemy(x);
        break;
      case 'destroyer':
        enemy = this.createDestroyerEnemy(x);
        break;
      case 'mothership':
        enemy = this.createMothershipEnemy(x);
        break;
    }
    
    world.addEntity(enemy);
  }

  private completeWave(waveManager: WaveManager, gameState: GameState): void {
    waveManager.isWaveActive = false;
    waveManager.waveStartTime = performance.now() / 1000;
    
    // 波次完成奖励
    const waveIndex = Math.min(waveManager.currentWave - 1, this.waveConfigs.length - 1);
    const bonusScore = this.waveConfigs[waveIndex].bonusScore;
    gameState.score += bonusScore;
    
    console.log(`✅ 第 ${waveManager.currentWave} 波完成！奖励分数: ${bonusScore}`);
    
    // 准备下一波
    waveManager.currentWave++;
    
    // 减少波次间隔时间（最小1秒）
    waveManager.timeBetweenWaves = Math.max(1, waveManager.timeBetweenWaves - 0.2);
  }

  // 敌机创建方法（从EnemySystem复制过来）
  private createScoutEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -30, rotation: Math.PI,
        velocityX: 0, velocityY: 150
      })
      .addComponent('renderer', {
        color: '#ff6666',
        radius: 12,
        shape: 'triangle' as const
      })
      .addComponent('collider', {
        radius: 12,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 25,
        max: 25
      })
      .addComponent('weapon', {
        fireRate: 2,
        lastFireTime: 0,
        damage: 10,
        bulletSpeed: 200,
        bulletColor: '#ff4444'
      })
      .addComponent('enemyAI', {
        type: 'scout',
        movePattern: 'zigzag',
        patternTime: 0
      });
  }

  private createDestroyerEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -40, rotation: Math.PI,
        velocityX: 0, velocityY: 100
      })
      .addComponent('renderer', {
        color: '#ff3333',
        radius: 18,
        shape: 'square' as const
      })
      .addComponent('collider', {
        radius: 18,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 75,
        max: 75
      })
      .addComponent('weapon', {
        fireRate: 1.2,
        lastFireTime: 0,
        damage: 20,
        bulletSpeed: 250,
        bulletColor: '#ff2222'
      })
      .addComponent('enemyAI', {
        type: 'destroyer',
        movePattern: 'straight',
        patternTime: 0
      });
  }

  private createMothershipEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -50, rotation: Math.PI,
        velocityX: 0, velocityY: 60
      })
      .addComponent('renderer', {
        color: '#cc0000',
        radius: 25,
        shape: 'circle' as const
      })
      .addComponent('collider', {
        radius: 25,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 200,
        max: 200
      })
      .addComponent('weapon', {
        fireRate: 0.8,
        lastFireTime: 0,
        damage: 30,
        bulletSpeed: 180,
        bulletColor: '#ff0000'
      })
      .addComponent('enemyAI', {
        type: 'mothership',
        movePattern: 'circle',
        patternTime: 0
      });
  }

  private shuffleArray<T>(array: T[]): void {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }
}